const userModel = require('../lib/mysql.js')
const moment = require('moment')
const md5 = require('md5')
    // const checkNotLogin = require('../middlewares/check.js').checkNotLogin
const checkLogin = require('../middlewares/check.js').checkLogin;
const md = require('markdown-it')();
const fs = require('fs')

/**
 * get/post查询用户列表页
 */
exports.getPosts = async ctx => {
    let res,
        postCount, { name } = ctx.request.body;
    // name = decodeURIComponent(ctx.request.querystring.split('=')[1]);
    // await checkLogin(ctx)
    if (ctx.request.body && Object.keys(ctx.request.body).length != 0) {
        await userModel.findAllUserCount()
            .then(result => {
                postCount = result[0].count
            })
        await userModel.findPostUserData(name)
            .then(result => {
                res = result
            })
        ctx.body = {
            session: ctx.session,
            posts: res,
            postsPageLength: Math.ceil(postCount / 10),
        }
    } else {
        await userModel.findAllUser()
            .then(result => {
                res = result
            })
        await userModel.findAllUserCount()
            .then(result => {
                postCount = result[0].count
            })
        ctx.body = {
            session: ctx.session,
            users: res,
            usersLength: postCount,
            usersPageLength: Math.ceil(postCount / 10),
        }
    }
}

/**
 * 删除指定id用户
 */
exports.postDeleteUser = async ctx => {
    let { userId } = ctx.request.body,
        allow;
    await userModel.findPostUserById(userId)
        .then(res => {
            console.log(res[0].name)
            console.log(ctx.session.user)
            if (res[0].name != ctx.session.user) {
                allow = false
            } else {
                allow = true
            }
        })
    if (allow) {
        await userModel.deleteUserById(userId)
            .then(() => {
                ctx.body = {
                    code: 200,
                    message: '删除用户成功'
                }
            }).catch(() => {
                ctx.body = {
                    code: 500,
                    message: '删除用户失败'
                }
            })
    } else {
        ctx.body = {
            code: 404,
            message: '无权限'
        }
    }
}

/**
 * 更新用户信息
 */
exports.upDateUserInfo = async ctx => {
    let { userId, name, password, repeatpass, avator, phone, email } = ctx.request.body,
        allowEdit = true
        // await checkLogin(ctx)
    await userModel.findPostUserById(userId)
        .then(res => {
            if (res[0].name != ctx.session.user) {
                allowEdit = false
            } else {
                allowEdit = true
            }
        })
    if (allowEdit) {
        if (password !== repeatpass || password.trim() === '') {
            ctx.body = {
                code: 500,
                message: '两次输入的密码不一致'
            };
        } else if (avator && avator.trim() === '') {
            ctx.body = {
                code: 500,
                message: '请上传头像'
            };
        } else {
            let base64Data = avator.replace(/^data:image\/\w+;base64,/, ""),
                dataBuffer = new Buffer(base64Data, 'base64'),
                getName = Number(Math.random().toString().substr(3)).toString(36) + Date.now(),
                upload = await new Promise((reslove, reject) => {
                    fs.writeFile('./public/images/' + getName + '.png', dataBuffer, err => {
                        if (err) {
                            throw err;
                            reject(false)
                        };
                        reslove(true)
                        console.log('头像上传成功')
                    });
                });
            if (upload) {
                await userModel.updatePostUser([name, phone, email, md5(password), avator, userId])
                    .then(() => {
                        ctx.body = {
                            code: 200,
                            message: '用户信息更新成功'
                        }
                    }).catch(() => {
                        ctx.body = {
                            code: 500,
                            message: '用户信息更新失败'
                        }
                    })
            } else {
                console.log('头像上传失败')
                ctx.body = {
                    code: 500,
                    message: '头像上传失败'
                }
            }
        }
    } else {
        ctx.body = {
            code: 404,
            message: '无权限'
        }
    }
}